package com.simpletour.qa.service.service;

import com.simpletour.qa.common.base.BaseBiz;
import com.simpletour.qa.service.entity.Solution;
import com.simpletour.qa.service.exception.CommonExceptionHandler;
import com.simpletour.qa.service.repository.SolutionRepository;
import com.simpletour.qa.service.rpc.UserService;
import com.simpletour.qa.service.util.UserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SolutionService extends BaseBiz<SolutionRepository, Solution, Integer> {

    public static final String DEFAULT_SOLUTION_ORDER_COLUMN = "createTime";

    private final static Logger LOG = LoggerFactory.getLogger(CommonExceptionHandler.class);

    @Autowired
    private SolutionRepository solutionRepository;

    @Autowired
    private UserService userService;

    public List<Solution> findByQuestionId(int page, int fetch, int questionId) {
        List<Solution> solutions = solutionRepository.findByQuestionId(questionId,
                PageRequest.of(page, fetch, Sort.Direction.DESC, DEFAULT_SOLUTION_ORDER_COLUMN));
        return solutions.parallelStream().map(s -> {
            s.setUser(UserUtil.convertUser(userService.findUserById(s.getUserId())));
            return s;
        }).collect(Collectors.toList());
    }

    public int findCountByQuestionId(Integer questionId) {

        return solutionRepository.findCountByQuestionId(questionId);
    }


    public List<Solution> findAll(int page, int fetch, Integer questionId) {
        if (questionId == null) {
            return findAll(page, fetch);
        }
        return findByQuestionId(page, fetch, questionId);
    }


    public List<Solution> findAll(int page, int fetch) {
        Page<Solution> solutionPage = solutionRepository.findAll(PageRequest.of(page, fetch,
                Sort.Direction.DESC, DEFAULT_SOLUTION_ORDER_COLUMN));
        System.out.println("page:" + page + "   fetch:" + fetch);
        return solutionPage.getContent().parallelStream().map(s -> {
            s.setUser(UserUtil.convertUser(userService.findUserById(s.getUserId())));
            return s;
        }).collect(Collectors.toList());
    }

    @Override
    public Solution save(Solution solution) {
        solution.setCreateTime(LocalDateTime.now());
        return super.save(solution);
    }
}
